<template>
    <div class="madp-article-list">
        <div class="madp-row">
            <h3 v-show="radio === 0">文章素材（共{{ articleData.length - 1 >= 0 ? articleData.length - 1 : 0 }}篇）</h3>
            <!-- <h3 v-show="radio === 1">文章素材（共{{ articleDataList.length }}篇）</h3> -->
            <el-input placeholder="请输入文章标题" class="madp-article-title" maxlength="20" v-model.trim="inputValue" @change="searchTitleBlurFn" clearable></el-input>
        </div>
        <div class="madp-article-content">
            <div class="madp-add-content" v-if="permissions.cp_marketing_material_add && radio === 1 && Array.isArray(officialAccount) && officialAccount.length === 0" @click="addContent">
                <i class="el-icon-circle-plus-outline"></i>
                <p>添加公众号</p>
            </div>
            <!-- 三种，那约定 1-未修改未发布，2-已发布，3-修改后未发布 -->
            <div v-if="radio === 0" class="madp-add-box">
                <div class="madp-add-content madp-add-list" v-for="(item, index) in articleData" :key="index">
                    <div class="madp-add-btn" v-if="item.add && permissions.cp_marketing_material_add" @click="addContent">
                        <i class="el-icon-circle-plus-outline"></i>
                        <p>添加文章</p>
                    </div>
                    <div class="madp-add-content-item" v-else>
                        <div class="madp-add-release v-else" v-show="item.marketingState == 1">
                            内容未发布 &nbsp;
                            <el-tooltip content="文章内容未进行发布审核，不支持发送给客户哦" placement="top" effect="light">
                                <i class="el-icon-question"></i>
                            </el-tooltip>
                        </div>
                        <div class="madp-add-release" v-show="item.marketingState == 3">
                            有修改内容未发布 &nbsp;
                            <el-tooltip content="文章内容未进行发布审核，不支持发送给客户哦" placement="top" effect="light">
                                <i class="el-icon-question"></i>
                            </el-tooltip>
                        </div>
                        <div class="madp-list-content">
                            <div class="madp-list-left">
                                <div class="list-title">{{ item.title }}</div>
                                <div class="list-desc">
                                    <p>{{ item.marketingDescribe }}</p>
                                </div>
                            </div>
                            <el-image class="madp-list-image" fit="contain" :src="item.marketingCover"></el-image>
                        </div>
                        <div class="madp-list-bottom">
                            <span>更新于{{ item.updateTime }}</span>
                            <div class="madp-list-bottom-btns">
                                <i class="el-icon-edit" v-if="permissions.cp_marketing_material_edit" @click="editRow(item)"></i>
                                <i class="el-icon-delete" v-if="radio === 0 && permissions.cp_marketing_material_del" @click="deleteRow(item)"></i>
                                <i class="el-icon-refresh" v-if="radio === 1" @click="refreshRow(item)"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 新增编辑文本 -->
        <el-dialog title="文章属性" v-if="dialogVisible" :visible.sync="dialogVisible" width="800px" :close-on-click-modal="false">
            <article-list-edit :radio="radio" :activeObj="activeObj" :sendArticleList="articleForm" @newAndEditArticleSaveFn="newAndEditArticleSaveFn" @weChatShowFn="weChatShowFn"></article-list-edit>
        </el-dialog>
        <el-dialog :visible.sync="weChatShow" width="20%" title="预览" :close-on-click-modal="false">
            <div class="madp-wechat-dialog">
                <el-image class="madp-wechat" fit="contain" :src="wechatUrl"></el-image>
            </div>
            <p class="madp-wechat-tips">
                <i class="el-icon-full-screen"></i>
                <span>请使用微信扫码预览</span>
            </p>
        </el-dialog>

        <el-dialog :visible.sync="officialAccountShow" width="800px" title="从已授权的公众号选择" :close-on-click-modal="false">
            <div class="madp-message-solid-type" v-show="radio === 1">
                <i class="el-icon-message-solid"></i>
                请选择满足 1、已认证服务号 2、绑定在企业微信开放平台的公众号，
                <a href="https://shimo.im/docs/gXqmevrxO6H8DWqo" target="_blank">如何绑定</a>
            </div>
            <div>
                <el-checkbox-group v-model="checkedItems" @change="handleCheckedItemsChange">
                    <el-checkbox v-for="item in officialAccountList" :label="item.authorizerAppId" :key="item.authorizerAppId" :value="item.authorizerAppId" class="madp-officialAccount-list-msg">
                        <div class="madp-officialAccount-list-name">
                            <el-image :src="item.headImg" class="madp-officialAccount-list-img" fit="cover"></el-image>
                            {{ item.nickName }}
                        </div>
                    </el-checkbox>
                </el-checkbox-group>
            </div>
            <div class="madp-dialog-footer">
                <a :href="authUrl" target="_blank">添加授权公众号</a>
                <span slot="footer">
                    <el-button @click="officialAccountListCancelFn">取消</el-button>
                    <el-button type="primary" @click="officialAccountSureFn">确定</el-button>
                </span>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import ArticleListEdit from './article-list-edit';
import { mapState, mapGetters } from 'vuex';
import {
    getArticleList,
    deleteArticle,
    articlePreview,
    // getAuthurl,
    getAccessToken,
    getAccessList,
    getDataList,
    getChangeAccessList,
    getDisplayAccessList,
    getMaterialList
} from '@/api/customer-into/marketing-material';
export default {
    components: {
        ArticleListEdit
    },
    props: {
        activeObj: {
            type: Object,
            default: () => {
                return {
                    activeIndex: 0
                };
            }
        }
    },
    computed: {
        ...mapState({
            marketingAuthCode: (state) => state.user.marketingAuthCode
        }),
        ...mapGetters(['permissions'])
    },
    watch: {
        activeObj() {
            if (this.activeObj.activeIndex > 1) {
                this.inputValue = '';
                if (this.radio === 0) {
                    this.getArticleListFn();
                }
            }
        }
    },
    data() {
        return {
            // loading开关
            loading: true,
            // 选中内容
            checkedItems: [],
            // 头像url
            authUrl: '',
            // 弹窗开关
            officialAccountShow: false,
            weChatShow: false,
            radio: 0,
            // 条件查询输入内容
            inputValue: null,
            // 文章数据
            articleData: [],
            articleDataList: [],
            // 文章表单
            articleForm: null,
            // 弹窗开关
            dialogVisible: false,
            // 图片路径
            wechatUrl: '',
            officialAccount: [],
            officialAccountList: [],
            officialAccountValue: {}, //选中公众号
            synchronizationTime: '2021-07-19 18:22',
            synchronizationLoading: false,
            ruleForm: {},
            showAuthorizerAppId: ''
        };
    },
    created() {
        if (this.radio === 0) {
            this.getArticleListFn();
        }
        // getAuthurl().then((res) => {
        // 	this.authUrl = res.data.data;
        // });
        // 判断公众号授权
        if (Object.keys(this.marketingAuthCode).length > 0) {
            let data = {
                appId: this.marketingAuthCode.component_appid,
                code: this.marketingAuthCode.auth_code
            };
            //授权
            getAccessToken(data).then((res) => {
                //获取公众号列表
                this.AccessList();
            });
            // this.AccessToken();
            // this.AccessList();
        } else {
            //获取公众号列表
            this.AccessList();
        }
    },
    mounted() {
        this.displayAccessList();
    },
    methods: {
        // /获取公众号accessToken
        // AccessToken(){
        //     let data={
        //         appId:this.marketingAuthCode.component_appid,
        //         code:this.marketingAuthCode.auth_code
        //     }
        //     getAccessToken(data).then((res)=>{
        //     })
        // },

        //获取授权公众号列表
        AccessList() {
            let data = {
                count: 100,
                offset: 0
            };
            getAccessList(data).then((res) => {
                if (res.data.code != 0) return;
                this.officialAccountList = res.data.data || [];
                this.totalAccount = res.data.data.totalCount;
            });
        },
        //选择展示的公众号
        handleCheckedItemsChange(val) {},
        //获取展示的公众号列表
        displayAccessList() {
            getDisplayAccessList().then((res) => {
                if (res.data.code === 0) {
                    this.officialAccount = res.data.data || [];
                    this.officialAccountValue = this.officialAccount && this.officialAccount[0];
                    this.showAuthorizerAppId = this.officialAccountValue ? this.officialAccountValue.authorizerAppId : '';
                    this.DataList();
                }
            });
        },
        // 获取公众号素材列表
        DataList() {
            let data = {
                appId: this.showAuthorizerAppId,
                classification: this.activeObj.id,
                count: 10,
                offset: 0
            };
            getDataList(data).then((res) => {
                this.MaterialList();
            });
        },
        //查询当前公众号的素材
        MaterialList(selectedKeys) {
            this.loading = true;
            if (selectedKeys) {
                const selectedRow = this.officialAccount.filter((item) => item.authorizerAppId === selectedKeys)[0];
                this.officialAccountValue = selectedRow;
                this.showAuthorizerAppId = selectedRow.authorizerAppId;
            }
            let data = {
                appId: this.showAuthorizerAppId,
                classification: this.activeObj.id,
                title: this.inputValue
            };
            getMaterialList(data)
                .then((res) => {
                    this.loading = false;
                    if (res.data.code === 0) {
                        this.articleDataList = res.data.data;
                    }
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        addContent() {
            if (this.radio === 0) {
                //添加文章
                this.addArticleContent();
            } else {
                //添加公众号
                this.addOfficialAccountFn();
            }
        },
        //   添加文章
        addArticleContent() {
            this.articleForm = {
                arBody: '',
                title: '',
                arAuthor: '',
                marketingDescribe: '',
                marketingCover: '',
                trackBehavior: false,
                trackDynamic: false,
                radio: this.radio,
                changeTitle: 0,
                classification: this.activeObj.id
            };
            this.dialogVisible = true;
        },
        // 编辑文章
        editRow(row) {
            this.articleForm = row;
            this.articleForm.changeTitle = 1;
            this.dialogVisible = true;
        },
        //删除文章
        deleteRow(row) {
            //   this.articleData.splice(row.id,1)
            this.deleteArticleFn(row.id);
        },
        // 同步文章
        refreshRow() {
            this.$message.success('同步成功');
        },
        //文章标题模糊查询或者分页查询
        getArticleListFn() {
            let obj = {
                title: this.inputValue,
                classification: this.activeObj.id
            };
            getArticleList(obj).then((res) => {
                if (res.data.code === 0) {
                    const newData = res.data.data || [];
                    newData.unshift({ add: true });
                    this.articleData = newData;
                }
            });
        },
        //删除文章
        deleteArticleFn(id) {
            deleteArticle(id).then((res) => {
                if (res.data.code === 0) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getArticleListFn();
                }
            });
        },
        newAndEditArticleSaveFn() {
            this.dialogVisible = false;
            this.getArticleListFn();
        },
        //模糊搜索
        searchTitleBlurFn() {
            if (this.radio === 0) {
                this.getArticleListFn();
            } else if (this.radio === 1) {
                this.MaterialList();
            }
        },
        weChatShowFn(data) {
            let obj = {
                classification: this.activeObj.id, //分类id
                arAttribute: data.radio, //文章属性，0为自有文章，1为公众号导入
                arAuthor: data.arAuthor, //文章作者
                arBody: data.arBody, //文章内容
                marketingCover: data.marketingCover, //文章封面
                marketingDescribe: data.marketingDescribe, //文章描述
                title: data.title, //文章标题
                trackBehavior: data.trackBehavior ? 1 : 0, //文章追踪-行为通知，0为未选中，1为选中，默认未选中
                trackDynamic: 1 //文章追踪-动态通知，0为未选中，1为选中，默认未选中
            };
            articlePreview(obj).then((res) => {
                if (res.data.code === 0) {
                    this.weChatShow = true;
                    this.wechatUrl = res.data.data;
                }
            });
        },
        // 同步
        synchronizationFn() {
            this.DataList();
            this.$message.success('同步成功！');
        },
        addOfficialAccountFn() {
            let officialAccountArr = [];
            let authorizerAppIds = [];
            this.officialAccount.map((item) => {
                officialAccountArr.push(item.nickName);
                authorizerAppIds.push(item.authorizerAppId);
            });
            this.checkedItems = authorizerAppIds;
            this.officialAccountList.map((item) => {
                let exit = officialAccountArr.indexOf(item.nickName);
                if (exit > -1) {
                    item.checked = true;
                } else {
                    item.checked = false;
                }
            });
            this.officialAccountShow = true;
        },
        // 取消
        officialAccountListCancelFn() {
            this.officialAccountShow = false;
        },
        // 确认
        officialAccountSureFn() {
            // let officialAccountArr = []
            // this.officialAccountList.map((item) => {
            //     if (item.checked) {
            //         officialAccountArr.push(item)
            //     }
            // })
            // this.officialAccount = officialAccountArr
            // if (this.officialAccount.length > 0) {
            //     this.officialAccountValue = this.officialAccount[0]
            // }
            if (this.checkedItems.length == 0) {
                this.$message.error('请勾选公众号！');
            } else {
                let appIds = this.checkedItems.join(',');
                let para = {
                    appIds: appIds
                };
                getChangeAccessList(para).then((res) => {
                    if (res.data.code == 0) {
                        this.displayAccessList();
                        this.officialAccountShow = false;
                    }
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-cancel-label {
    color: #000;
}
.madp-row {
    margin-top: 10px;
    height: 40px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
}
.madp-article-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    margin-top: 10px;
    .madp-add-content {
        display: flex;
        cursor: pointer;
        width: 260px;
        min-height: 160px;
        height: 9.2rem;
        border: 1px solid #dcdfe6;
        margin: 10px;
        box-sizing: border-box;
        padding: 6px;
        .el-icon-circle-plus-outline {
            font-size: 20px;
        }
    }
}
.madp-add-box {
    display: flex;
    flex-wrap: wrap;
}
.madp-add-btn {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin: 0 auto;
    align-items: center;
}
.madp-add-list {
    position: relative;
    .madp-add-release {
        position: absolute;
        right: 0;
        top: 0;
        z-index: 10;
        font-size: 12px;
        cursor: pointer;
        width: fit-content;
        height: 20px;
        background: rgba(220, 223, 230, 0.8);
        text-align: right;
        border-radius: 2px;
    }
    .madp-add-content-item {
        width: 100%;
    }
    .madp-list-content {
        display: flex;
        justify-content: space-between;
        .madp-list-left {
            width: calc(100% - 6.25rem);
            .list-title {
                font-size: 16px;
                font-weight: bold;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
            }
        }
    }

    .list-desc p {
        width: 100%;
        height: 2.4rem;
        line-height: 1.2rem;
        font-size: 0.7rem;
        word-break: break-all;
        text-overflow: ellipsis;
        display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
        -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
        -webkit-line-clamp: 2; /** 显示的行数 **/
        overflow: hidden; /** 隐藏超出的内容 **/
    }
    .madp-list-image {
        max-width: 80px;
        height: 80px;
    }
    .madp-list-bottom {
        height: fit-content;
        width: 100%;
        font-size: 0.75rem;
        border-top: 0.0625rem solid #dcdfe6;
        display: flex;
        padding: 6px 6px 0 0;
        position: absolute;
        bottom: 0;
        left: 0;
        justify-content: space-between;
        span {
            margin-left: 5px;
        }
        .el-icon-edit {
            font-size: 20px;
            margin-left: 10px;
            cursor: pointer;
        }
        .el-icon-delete {
            font-size: 20px;
            margin-left: 10px;
            cursor: pointer;
        }
        .el-icon-refresh {
            font-size: 20px;
            margin-left: 10px;
            cursor: pointer;
        }
        &-btns {
            display: flex;
        }
    }
}
.madp-wechat-dialog {
    display: flex;
    justify-content: center;
}
.madp-wechat-tips {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    align-items: center;
    span {
        font-size: 18px;
    }
}
.madp-wechat {
    width: 80%;
}
.el-icon-full-screen {
    font-size: 20px;
    color: #1890ff;
    margin-right: 8px;
}
.madp-article-title {
    width: 20%;
}
.madp-official-account {
    position: relative;
    /deep/ .el-select-dropdown__item {
        display: flex !important;
        align-items: center !important;
    }
    /deep/ .el-select-dropdown__item:hover {
        display: flex !important;
        align-items: center !important;
    }
    /deep/ .el-input__inner {
        padding-left: 60px;
    }
    #madp-selimg {
        position: absolute;
        top: 6px;
        width: 24px;
        height: 24px;
        object-fit: cover;
        left: 20px;
        z-index: 99;
    }
}
.madp-avatar {
    float: left;
    width: 28px;
    height: 28px;
    margin-top: 5px !important;
    margin-right: 15px !important;
    object-fit: cover;
}
.madp-official-account-msg {
    margin: 20px 0px;
    display: flex;
    justify-content: space-between;
    span {
        margin-right: 20px;
    }
}
.madp-message-solid {
    display: inline-block;
    margin-left: 20px;
}
.madp-message-solid-type {
    background: #effaff;
    padding: 10px;
    .el-icon-message-solid {
        color: #ed5555;
    }
}
.madp-officialAccount-list-msg {
    border: 1px solid #eee;
    padding: 10px 19px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    .madp-officialAccount-list-name {
        display: flex;
        align-items: center;
    }
}
.madp-add-official-account {
    padding: 0 20px;
}
.madp-officialAccount-list-img {
    border-radius: 4px;
    width: 40px;
    height: 40px;
    margin-right: 10px;
}
a {
    text-decoration: none;
    color: #ed5555;
    cursor: pointer;
}
.madp-dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 40px;
}
/deep/.el-checkbox {
    margin-right: 0px !important;
}
.madp-buttons {
    display: flex;
    justify-content: center;
}
</style>
